package com.qf.springbootproject.shiro;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.qf.springbootproject.user.entity.Users;
import com.qf.springbootproject.user.service.UsersService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UsersService userService;

    /**
     * 通过这个方法 向shiro提供当前用户的权限相关信息
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


        return null;
    }


    /**
     * 通过这个方法 向shrio提供 当前用户的身份印证信息
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", username);
        Users user = userService.getOne(usersQueryWrapper);
        if (user == null) {
            throw new UnknownAccountException("用户不存在");
        }
        //把数据库密码返回shiro(第一个参数可以放user 或字符串，是object类型) //影响后续从shiro中取出对象的类型
        //第二个参数放入数据库中查询的密码
        //第三个是当前提供身份信息的realm名字
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(user, user.getPassword(),
                        ByteSource.Util.bytes(user.getSalt()),//把当前用户的盐给shiro
                        this.getName());

        return simpleAuthenticationInfo;
    }


}


